package com.myblog.config.security.handle;

import com.alibaba.fastjson.JSON;
import com.myblog.common.ResultInfoFactory;
import com.myblog.config.properties.SecurityProperties;
import com.myblog.config.security.authorize.AuthenticationSuccessListener;
import com.myblog.emun.LoginResponseType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("customAuhtenticationSuccessHandler")
@Slf4j
public class CustomAuhtenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired(required = false)//不一定要实现 有则注入容器中
    private AuthenticationSuccessListener authenticationSuccessListener;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        if(authenticationSuccessListener!=null){
            authenticationSuccessListener.successListener( httpServletRequest,  httpServletResponse,  authentication);
        }
        if(LoginResponseType.JSON.equals(securityProperties.getLoginResponseType())){
            ResultInfoFactory result = new ResultInfoFactory();
            result.setMessage("认证成功");
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(result.toJsonString(result));
        }else {
            log.info("authentication={},", JSON.toJSONString(authentication));
            super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
        }

    }

}
